#include <iostream>
#include <cstring>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"

using namespace std;

void usage(string proc)
{
    std::cout << "Usage:\n\t" << proc << " port\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    // 1.socket
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "套接字创建失败：" << strerror(errno) << endl;
    }

    // connect
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &(server.sin_addr));

    int cnt = 5;
    while (connect(sock, (struct sockaddr *)&server, sizeof(server) != 0))
    {
        sleep(1);
        cout << "正在重连，次数还有：" << cnt-- << endl;
        if(cnt <= 0)
        {
            break;
        }
    }
    if (cnt <= 0)
    {
        cerr << "连接失败" << endl;
        exit(CONNECT_ERR);
    }

    char buffer[1024];
    while (true)
    {
        string line;
        cout << "请输入>>> ";
        getline(cin, line);

        // 将数据写给服务器
        write(sock, line.c_str(), line.size());

        // 读取服务器发回的数据
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "服务器回显>>> " << buffer << endl;
        }
        else if (s == 0)
        {
            close(sock);
            cerr << "服务器关闭" << endl;
            break;
        }
        else
        {
            close(sock);
            cerr << "从服务器读取数据失败:" << strerror(errno) << endl;
            break;
        }
    }

    return 0;
}